import { app, BrowserWindow, shell, ipcMain, Menu, dialog  } from 'electron'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import os from 'node:os' //获取操作系统信息
import { update } from './update'
import fs from 'node:fs'

const _require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))

// The built directory structure
//
// ├─┬ dist-electron
// │ ├─┬ main
// │ │ └── index.js    > Electron-Main
// │ └─┬ preload
// │   └── index.mjs   > Preload-Scripts
// ├─┬ dist
// │ └── index.html    > Electron-Renderer
//
process.env.APP_ROOT = path.join(__dirname, '../..')

export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')
export const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
  ? path.join(process.env.APP_ROOT, 'public')
  : RENDERER_DIST

// Disable GPU Acceleration for Windows 7
if (os.release().startsWith('6.1')) app.disableHardwareAcceleration()

// Set application name for Windows 10+ notifications
if (process.platform === 'win32') app.setAppUserModelId(app.getName())

if (!app.requestSingleInstanceLock()) {
  app.quit()
  process.exit(0)
}

let win: BrowserWindow | null = null
const preload = path.join(__dirname, '../preload/index.mjs')
const indexHtml = path.join(RENDERER_DIST, 'index.html')
const fsPromises = fs.promises
// 打开模型文件对话框
async function openModelFileDialog(): Promise<{ path: string; buffer: Buffer } | null> {
  if (!win) return null

  const result = await dialog.showOpenDialog(win, {
    title: '选择模型文件',
    properties: ['openFile'],
    filters: [{ name: '模型文件', extensions: ['gltf', 'glb'] }],
  })

  if (result.canceled || result.filePaths.length === 0) {
    return null
  }

  const filePath = result.filePaths[0]
  const buffer = await fsPromises.readFile(filePath)
  
  // 返回文件路径和内容
  return { path: filePath, buffer }
}

async function createWindow() {
  win = new BrowserWindow({
    title: '主窗口',
    icon: path.join(process.env.VITE_PUBLIC, 'favicon.ico'),
    webPreferences: {
      preload,
      // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production
      // nodeIntegration: true,

      // Consider using contextBridge.exposeInMainWorld
      // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation
      // contextIsolation: false,
    },
  })

  if (VITE_DEV_SERVER_URL) {
    // #298
    win.loadURL(VITE_DEV_SERVER_URL)
    // Open devTool if the app is not packaged
    win.webContents.openDevTools()
  } else {
    win.loadFile(indexHtml)
  }

  // Test actively push message to the Electron-Renderer
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', new Date().toLocaleString())
  })

  // Make all links open with the browser, not with the application
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('https:')) shell.openExternal(url)
    return { action: 'deny' }
  })

  // Auto update
  update(win)
}

// 创建中文菜单栏
function createMenu() {
  const template: Electron.MenuItemConstructorOptions[] = [
    {
      label: '文件',
      submenu: [
        {
          label: '新建窗口',
          accelerator: 'CmdOrCtrl+N',
          click: () => {
            // 创建新窗口的逻辑
            const newWindow = new BrowserWindow({
              title: '新窗口',
              webPreferences: {
                preload: path.join(__dirname, '../preload/index.mjs'),
              },
            })
            if (VITE_DEV_SERVER_URL) {
              newWindow.loadURL(VITE_DEV_SERVER_URL)
            } else {
              newWindow.loadFile(path.join(RENDERER_DIST, 'index.html'))
            }
          },
        },
        {
          label: '打开模型',
          accelerator: 'CmdOrCtrl+O',
          click: async () => {
            const fileData = await openModelFileDialog()
            if (fileData && win) {
              const arrayBuffer = fileData.buffer.buffer.slice(
                fileData.buffer.byteOffset,
                fileData.buffer.byteOffset + fileData.buffer.byteLength
              )
              win.webContents.send('model-file-selected', {
                path: fileData.path,
                buffer: new Uint8Array(arrayBuffer),
              })
            }
          },
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit()
          },
        },
      ],
    },
    {
      label: '编辑',
      submenu: [
        { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
      ],
    },
    {
      label: '查看',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'CmdOrCtrl+Shift+R', role: 'forceReload' },
        {
          label: '切换开发者工具',
          accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Ctrl+Shift+I',
          role: 'toggleDevTools',
        },
        { type: 'separator' },
        {
          label: '切换主题',
          accelerator: 'CmdOrCtrl+T',
          click: () => {
            // 通知渲染进程切换主题
            win?.webContents.send('theme-toggle')
          },
        },
        { type: 'separator' },
        {
          label: '暗色主题',
          type: 'radio',
          checked: currentTheme === 'dark',
          id: 'theme-dark',
          click: () => {
            currentTheme = 'dark'
            updateMenuTheme('dark')
            win?.webContents.send('theme-changed', 'dark')
          },
        },
        {
          label: '亮色主题',
          type: 'radio',
          checked: currentTheme === 'light',
          id: 'theme-light',
          click: () => {
            currentTheme = 'light'
            updateMenuTheme('light')
            win?.webContents.send('theme-changed', 'light')
          },
        },
        // { type: 'separator' },
        // { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
        // { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
        // { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
        // { type: 'separator' },
        // { label: '全屏', accelerator: 'F11', role: 'togglefullscreen' }
      ],
    },
    {
      label: '窗口',
      submenu: [
        { label: '最小化', accelerator: 'CmdOrCtrl+M', role: 'minimize' },
        { label: '关闭', accelerator: 'CmdOrCtrl+W', role: 'close' },
      ],
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            // 显示关于对话框
            dialog.showMessageBox(win!, {
              type: 'info',
              title: '关于',
              message: 'Electron + Vite + React',
              detail: '这是一个基于 Electron、Vite 和 React 的桌面应用程序。',
            })
          },
        },
      ],
    },
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

app.whenReady().then(() => {
  createWindow()
  createMenu()
})

app.on('window-all-closed', () => {
  win = null
  if (process.platform !== 'darwin') app.quit()
})

app.on('second-instance', () => {
  if (win) {
    // Focus on the main window if the user tried to open another
    if (win.isMinimized()) win.restore()
    win.focus()
  }
})

app.on('activate', () => {
  const allWindows = BrowserWindow.getAllWindows()
  if (allWindows.length) {
    allWindows[0].focus()
  } else {
    createWindow()
  }
})

// New window example arg: new windows url
ipcMain.handle('open-win', (_, arg) => {
  const childWindow = new BrowserWindow({
    webPreferences: {
      preload,
      nodeIntegration: true,
      contextIsolation: false,
    },
  })

  if (VITE_DEV_SERVER_URL) {
    childWindow.loadURL(`${VITE_DEV_SERVER_URL}#${arg}`)
  } else {
    childWindow.loadFile(indexHtml, { hash: arg })
  }
})

ipcMain.handle('open-model-file', async () => {
  console.log('🚀 ~ open-model-file: ~ openModelFileDialog:')
  return await openModelFileDialog()
})

// 当前主题状态
let currentTheme: 'light' | 'dark' = 'dark'

// 主题相关 IPC 处理
ipcMain.on('theme-init', (_, theme: 'light' | 'dark') => {
  // 渲染进程初始化时发送当前主题，更新菜单状态
  currentTheme = theme
  updateMenuTheme(theme)
})

ipcMain.on('theme-changed', (_, theme: 'light' | 'dark') => {
  // 渲染进程主题更改时，更新菜单状态
  currentTheme = theme
  updateMenuTheme(theme)
})

// 更新菜单中主题选项的状态
function updateMenuTheme(theme: 'light' | 'dark') {
  const menu = Menu.getApplicationMenu()
  if (!menu) return

  const viewMenu = menu.items.find(item => item.label === '查看')
  if (!viewMenu || !viewMenu.submenu) return

  const submenu = viewMenu.submenu as Electron.Menu

  // 通过 ID 查找菜单项更可靠
  const darkItem = submenu.getMenuItemById('theme-dark')
  const lightItem = submenu.getMenuItemById('theme-light')

  if (darkItem) darkItem.checked = theme === 'dark'
  if (lightItem) lightItem.checked = theme === 'light'
}
